import { Injectable } from '@angular/core';
import { TreeNode } from '@farris/ui-treetable';
import { FormSchemaEntityField } from '@farris/designer-services';

@Injectable()
export class VariableContrastService {

    newVarList: FormSchemaEntityField[];
    oldVarList: FormSchemaEntityField[];

    varTreeData: TreeNode[] = [];

    getVariableTree(newVarList: FormSchemaEntityField[], oldVarList: FormSchemaEntityField[]): TreeNode[] {

        this.newVarList = newVarList;
        this.oldVarList = oldVarList || [];
        this.varTreeData = [];
        this.getAddedVars();
        this.getModifiedVars();

        return this.varTreeData;
    }

    private getAddedVars() {
        this.newVarList.forEach(newVar => {

            const oldVar = this.oldVarList.find(f => f.id === newVar.id);
            if (!oldVar) {
                this.varTreeData.push({
                    data: { ...newVar, modifyType: '新增' }, selectable: true
                });
            }
        });
    }

    private getModifiedVars() {
        const deleted = [];
        const modified = [];
        this.oldVarList.forEach(oldVar => {

            const newVar = this.newVarList.find(f => f.id === oldVar.id);
            if (!newVar) {
                deleted.push({ data: { ...oldVar, modifyType: '删除' }, selectable: true, });
            } else {
                // 简单比较
                delete oldVar['category'];
                if (JSON.stringify(newVar) !== JSON.stringify(oldVar)) {
                    modified.push({ data: { ...oldVar, modifyType: '修改' }, selectable: true });
                }
            }
        });

        this.varTreeData.push(...deleted);
        this.varTreeData.push(...modified);
    }
}
